package com.zbkj.crmeb.task.order;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.SmsConstants;
import com.utils.MessageUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.sms.model.CmsMessageConfig;
import com.zbkj.crmeb.sms.request.SendSmsVo;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.service.PurchaseGoodsService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.service.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 提醒商家发货
 */
@Component
@Configuration
@Slf4j
public class RemindMerToDeliverGoodsTask {

    @Value("${message.remind-delivery}")
    private boolean remindDelivery;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private PurchaseGoodsService purchaseGoodsService;
    @Autowired
    private SupplierService supplierService;

	@XxlJob("remindMerToDeliverGoodsTask")
    public void init(){
        log.info("-----------------执行提醒商家发货定时任务-------------------");
        if(!remindDelivery) {
            return;
        }
        //自建商品待发货订单数量
        List<StoreOrder> BacklogOrderList = storeOrderService.getBacklogOrderQuantity();
        if(CollectionUtils.isNotEmpty(BacklogOrderList)){
            Map<Integer, Integer> map = BacklogOrderList.stream().collect(Collectors.toMap(StoreOrder::getMerId, StoreOrder::getTotalNum));
            List<Integer> merIdList = BacklogOrderList.stream().map(StoreOrder::getMerId).collect(Collectors.toList());
            List<ChannelMerchant> channelMerchantList = channelMerchantService.list(Wrappers.lambdaQuery(ChannelMerchant.class).in(ChannelMerchant::getId, merIdList));
            channelMerchantList.forEach(e->{
                try {
                    if (map.containsKey(e.getId())) {
                        SendSmsVo sendSmsVo = new SendSmsVo();
                        sendSmsVo.setMobiles(e.getContactPhone());
                        sendSmsVo.setSendEnable("true");
                        String areaCode = e.getAreaCode().trim();
                        if(areaCode.startsWith("+")){
                            areaCode = areaCode.substring(1);
                        }
                        sendSmsVo.setNationCode(areaCode);
                        String params = JSONObject.toJSONString(Stream.of(e.getChannelName(),map.get(e.getId()).toString()).collect(Collectors.toList()));
                        sendSmsVo.setParam(params);
                        CmsMessageConfig messageConfig = new CmsMessageConfig();
                        messageConfig.setAppId(SmsConstants.SMS_APPID);
                        messageConfig.setAppKey(SmsConstants.SMS_APPKEY);
                        messageConfig.setTemplateId(SmsConstants.SMS_REMIND_TO_DELIVER_TEMPLATE_ID);
                        messageConfig.setSmsSign(SmsConstants.SMS_SUYUN_SIGN);
                        MessageUtils.sendMessage(Boolean.TRUE, sendSmsVo, messageConfig);
                        log.info("-----------提醒商家发货短信发送成功,号码:{}-----------------", e.getContactPhone());
                    }
                }catch (Exception e1){
                    log.info("-----------------提醒商家发货短信发送失败,号码:{},{}-------------------",e.getContactPhone(),e1.getMessage());
                }
            });
        }
    }

    @XxlJob("remindSupplierConfirmGoodsTask")
    public void remindSupplierConfirm(){
        log.info("-----------------执行提醒供应商确认商品定时任务-------------------");
        if(!remindDelivery) {
            return;
        }
        //查询系统所有供应商
        List<ChannelMerchant> merchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery().eq(ChannelMerchant::getChannelType, 3)
                .select(ChannelMerchant::getId,ChannelMerchant::getSuppliersIds,ChannelMerchant::getAreaCode,ChannelMerchant::getContactPhone));
        if(CollectionUtils.isEmpty(merchantList)){
            return;
        }
        Map<Integer, Integer> merchantMap = merchantList.stream().collect(Collectors.toMap(ChannelMerchant::getId,
                e-> JSONArray.parseArray(e.getSuppliersIds(), Integer.class).get(0)));
        //获取供应商is_europe
        List<Supplier> exitSupplierList = supplierService.list(Wrappers.<Supplier>lambdaQuery().in(Supplier::getId, merchantMap.values()).isNotNull(Supplier::getIsEurope)
                .select(Supplier::getId,Supplier::getIsEurope));
        Map<Integer, Integer> supplierMap = exitSupplierList.stream().collect(Collectors.toMap(Supplier::getId, Supplier::getIsEurope));
        //查询待确认订单
        List<PurchaseGoods> purchaseGoodsList = purchaseGoodsService.list(Wrappers.<PurchaseGoods>lambdaQuery().eq(PurchaseGoods::getStatus, 6)
                .in(PurchaseGoods::getChannelType, supplierMap.values()).select(PurchaseGoods::getId,PurchaseGoods::getChannelType));
        if(CollectionUtils.isNotEmpty(purchaseGoodsList)){
            Map<Integer, List<PurchaseGoods>> goodsMapByType = purchaseGoodsList.stream().collect(Collectors.groupingBy(PurchaseGoods::getChannelType));
            for (ChannelMerchant merchant : merchantList) {
                try {
                    Integer supplierId = merchantMap.get(merchant.getId());
                    Integer isEurope = supplierMap.get(supplierId);
                    if(Objects.isNull(isEurope)){
                       continue;
                    }
                    List<PurchaseGoods> purchaseGoods = goodsMapByType.get(isEurope);
                    if(CollectionUtils.isEmpty(purchaseGoods)){
                        continue;
                    }
                    SendSmsVo sendSmsVo = new SendSmsVo();
                    sendSmsVo.setMobiles(merchant.getContactPhone());
                    String areaCode = merchant.getAreaCode().trim();
                    if(areaCode.startsWith("+")){
                        areaCode = areaCode.substring(1);
                    }
                    sendSmsVo.setNationCode(areaCode);
                    sendSmsVo.setSendEnable("true");
                    String params = JSONObject.toJSONString(Stream.of(String.valueOf(purchaseGoods.size())).collect(Collectors.toList()));
                    sendSmsVo.setParam(params);
                    CmsMessageConfig messageConfig = new CmsMessageConfig();
                    if(areaCode.equals("86") || StringUtils.isBlank(areaCode)){
                        messageConfig.setTemplateId(SmsConstants.SMS_REMIND_SUPPLIER_CONFIRM_TEMPLATE_CN_ID);
                        messageConfig.setSmsSign(SmsConstants.SMS_SUYUN_SIGN);
                    }else {
                        messageConfig.setTemplateId(SmsConstants.SMS_REMIND_SUPPLIER_CONFIRM_TEMPLATE_EN_ID);
                        messageConfig.setSmsSign(SmsConstants.SMS_SUYUN_SIGN_EN);
                    }
                    messageConfig.setAppId(SmsConstants.SMS_APPID);
                    messageConfig.setAppKey(SmsConstants.SMS_APPKEY);
                    MessageUtils.sendMessage(Boolean.TRUE, sendSmsVo, messageConfig);
                    log.info("-----------提醒供应商确认订单短信发送成功,号码:{}-----------------", merchant.getContactPhone());
                }catch (Exception e1){
                    log.info("-----------------提醒供应商确认订单短信发送失败,号码:{},{}-------------------",merchant.getContactPhone(),e1.getMessage());
                }
            }
        }
    }

}
